package org.apache.logging.log4j2.solon.integration;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.noear.solon.Solon;
import org.noear.solon.Utils;
import org.noear.solon.core.util.LogUtil;
import org.noear.solon.core.util.ResourceUtil;
import org.noear.solon.logging.LogIncubator;
import org.noear.solon.logging.LogOptions;
import org.noear.solon.logging.model.LoggerLevelEntity;
import org.springframework.boot.logging.log4j2.Log4J2LoggingSystem;

/**
 * 日志孵化器
 *
 * @author noear
 * @since 2.4
 */
public class LogIncubatorImpl implements LogIncubator {
    @Override
    public void incubate() throws Throwable {
        //尝试从配置里获取
        URL url = getUrlOfConfig();

        //尝试包内定制加载
        if (url == null) {
        	url = _loadLog4j2();
        }

        initDo(url);
    }
    
    private URL _loadLog4j2() {
    	String[] xml = new String[] { "log4j2.xml", "log4j2-spring.xml","log4j2-spring-" + Solon.cfg().env() + ".xml", "log4j2-file.xml","log4j2-file-" + Solon.cfg().env() + ".xml"};
    	URL url=null;
    	for(String f:xml) {
			url = ResourceUtil.getResource(f);
			if(url!=null) {
				break;
			}
		}
		return url;
    }



    private void initDo(URL url) {
        if (url == null) {
            return;
        }

        try {
        	Configurator.reconfigure(url.toURI());
//        	LoggerContext context = LoggerContext.getContext(false);
//        	Log4J2LoggingSystem log4J2LoggingSystem = new Log4J2LoggingSystem();
//        	log4J2LoggingSystem.initialize(context, url);
            //同步 logger level 配置
            if (LogOptions.getLoggerLevels().size() > 0) {
            	LoggerContext context = LoggerContext.getContext(false);
                for (LoggerLevelEntity lle : LogOptions.getLoggerLevels()) {
                    LoggerConfig logger = new LoggerConfig(lle.getLoggerExpr(),
                            Level.valueOf(lle.getLevel().name()),
                            true);
                    context.getConfiguration().addLogger(logger.getName(), logger);
                }

                context.updateLoggers();
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * 基于配置，获取日志配置文件
     */
    private URL getUrlOfConfig() throws MalformedURLException {
        String logConfig = Solon.cfg().get("logging.config");

        if (Utils.isNotEmpty(logConfig)) {
            File logConfigFile = new File(logConfig);
            if (logConfigFile.exists()) {
                return logConfigFile.toURI().toURL();
            } else {
                LogUtil.global().warn("Props: No log config file: " + logConfig);
            }
        }

        return null;
    }
}
